﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Abp.Application.Services;
using Abp.IdentityFramework;
using Abp.Runtime.Session;
using FwProject.Authorization.Users;
using FwProject.MultiTenancy;
using System.Linq;
using System.IO;

namespace FwProject.ShopApplication
{
    /// <summary>
    /// Derive your application services from this class.
    /// </summary>
    public abstract class FwProjectAppServiceBase : ApplicationService
    {
        public TenantManager TenantManager { get; set; }

        public UserManager UserManager { get; set; }

        protected FwProjectAppServiceBase()
        {
            LocalizationSourceName = FwProjectConsts.LocalizationSourceName;
        }

        protected virtual Task<User> GetCurrentUserAsync()
        {
            var user = UserManager.FindByIdAsync(AbpSession.GetUserId().ToString());
            if (user == null)
            {
                throw new Exception("There is no current user!");
            }

            return user;
        }

        protected virtual Task<Tenant> GetCurrentTenantAsync()
        {
            return TenantManager.GetByIdAsync(AbpSession.GetTenantId());
        }

        protected virtual void CheckErrors(IdentityResult identityResult)
        {
            identityResult.CheckErrors(LocalizationManager);
        }



        /// <summary>
        /// 将用户上传的临时文件保存(move)到正式文件夹(含为空验证)
        /// </summary>
        /// <param name="file">文件（可包含除tempFileUrlPrefix部分路径，多个以'|'号隔开）</param>
        /// <param name="tempFileUrlPrefix">临时文件夹</param>
        /// <param name="saveFileUrlPrefix">保存文件夹</param>
        /// <param name="prefixPath">如果量大可加上时间作为路径的一部分 ex: DateTime.Now.ToString("yyyyMMdd")+"/"</param>
        /// <param name="oldFile">旧文件（新文件保存成功后会将其删除，多个以'|'号隔开）</param>
        /// <param name="validateFile">验证文件合法性，代入的是file去除部分路径之后的值</param>
        /// <returns>prefixPath+文件名（多个以'|'号隔开）||oldFile||null</returns>
        protected virtual string SaveFile(string file, string tempFileUrlPrefix, string saveFileUrlPrefix, string prefixPath = null, string oldFile = null, Func<string, bool> validateFile = null)
        { 
            if (string.IsNullOrEmpty(file))
                return null;
            string[] files = file.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            if (files.Length == 0)
                return null;
            string[] oldFiles = null;
            if (!string.IsNullOrEmpty(oldFile))
            {
                oldFiles = oldFile.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                if (oldFiles.Length > 0)//删除旧文件
                {
                    var removedFiles = oldFiles.Where(o => !files.Contains(o)).ToList();
                    foreach (string of in removedFiles)
                        DeleteFile(of, saveFileUrlPrefix);
                }
            }
            for (int i = 0; i < files.Length; i++)
            {
                if (oldFiles == null || !oldFiles.Contains(files[i]))
                {
                    //FileInfo fi = new FileInfo(Path.Combine(webroot, tempFileUrlPrefix + files[i]));// ; HostingEnvironment.MapPath(tempFileUrlPrefix + files[i])http://stackoverflow.com/questions/944219/what-is-the-difference-between-server-mappath-and-hostingenvironment-mappath HttpContext.Current.Server.MapPath(tempFileUrlPrefix + files[i])
                    FileInfo fi = new FileInfo(Path.Combine(tempFileUrlPrefix,files[i]));
                    if (fi.Exists)
                    {
                        if (files[i].Contains("/"))
                            files[i] = files[i].Substring(files[i].LastIndexOf('/') + 1);//去除包含的部分路径
                        if (validateFile == null || validateFile(files[i]))
                        {
                            //string savePath = Path.Combine(webroot, saveFileUrlPrefix + prefixPath);//HttpContext.Current.Server.MapPath(saveFileUrlPrefix + prefixPath);
                            string savePath = Path.Combine(saveFileUrlPrefix, prefixPath);
                            if (!Directory.Exists(savePath))
                                Directory.CreateDirectory(savePath);
                            fi.MoveTo(Path.Combine(savePath, files[i]));

                            files[i] = prefixPath + files[i];
                        }
                        else
                            Logger.Warn($"{tempFileUrlPrefix}{files[i]}文件格式不正确。"); //throw new UserFriendlyException(2, "文件格式不正确！");
                    }
                }
            }
            return string.Join("|", files);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="file">文件（多个以'|'号隔开）</param>
        /// <param name="saveFileUrlPrefix">保存文件夹</param>
        protected virtual void DeleteFile(string file,string webroot)
        {
            if (!string.IsNullOrEmpty(file))
            {
                string[] files = file.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                if (files.Length > 0)
                {
                    foreach (string f in files)
                    {
                        try
                        {
                          var filePath = Path.Combine(webroot, f);//HttpContext.Current.Server.MapPath(saveFileUrlPrefix + file);HostingEnvironment.MapPath(file); 
                          File.Delete(filePath);
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn($"尝试删除文件 {file} 失败，错误信息：{ex.Message}。");//{saveFileUrlPrefix}{file}
                        }
                    }
                }
            }
        }
    }
}
